<?php


namespace services\rbac;


use common\components\Service;
use common\models\member\Member;
use common\models\rbac\RolePermission;
use services\member\MemberService;
use Yii;

class RolePermissionService extends Service
{
    /**
     * 获取用户权限
     * @param Member|null $member
     * @return array
     */
    public function getMemberPermissions(?Member $member): array
    {
        $return = [
//            'header' => [],
            'sider' => [],
            'action' => [],
        ];

        if (empty($member)) {
            return $return;
        }
        // 用户【菜单 + 动作】
        $auth = MemberService::getMemberLimitData($member);
        // 菜单列表
        $return['sider'] = $this->getMenuListFormat($auth['menu']);
        // 动作列表
        $return['action'] = $this->getActionListFormat($auth['action']);
        // 模块列表
//        $return['header'] = $this->getModuleListFormat($moduleList);

        return $return;
    }

    /**
     * 根据角色IDs获取绑定关联列表
     * @param int $type
     * @param $roleIds
     * @return RolePermission[]
     */
    public static function getRolePermissionListByRoleIds(int $type, $roleIds): array
    {
        return RolePermission::find()
            ->where([
                'role_id' => $roleIds,
                'permission_type' => $type
            ])
            ->all();
    }

    /**
     * 根据角色IDs获取绑定关联列表
     * @param int $type
     * @param $roleIds
     * @return RolePermission[]
     */
    public static function getRolePermissionListByPermissionIds(int $type, $permissionIds): array
    {
        return RolePermission::find()
            ->where([
                'permission_id' => $permissionIds,
                'permission_type' => $type
            ])
            ->all();
    }

    /**
     * 获取角色绑定动作列表
     * @param array $roleIds 角色IDs
     * @return array
     */
    public static function getActionList(array $roleIds): array
    {
        if (empty($roleIds)) {
            return [];
        }

        $permissionIds = array_column(self::getRolePermissionListByRoleIds(RolePermission::PERMISSION_TYPE_ACTION, $roleIds), 'permission_id');
        return ActionService::getEnableListByIds($permissionIds);
    }

    /**
     * 获取角色绑定菜单列表
     * @param array $roleIds 角色IDs
     * @return array
     */
    public static function getMenuList(array $roleIds): array
    {
        if (empty($roleIds)) {
            return [];
        }

        $permissionIds = array_column(self::getRolePermissionListByRoleIds(RolePermission::PERMISSION_TYPE_MENU, $roleIds), 'permission_id');
        return MenuService::getEnableListByIds($permissionIds);
    }

    /**
     * 格式化动作列表
     * @param array $data 查询结果【getActionList】
     * @return array
     */
    public function getActionListFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'flag' => $row['flag'],
                'name' => $row['name'],
                'marking' => $row['marking'],
            ];
        }

        return $list;
    }

    /**
     * 格式化菜单数据
     * @param array $data 查询结果【getMenuList】
     * @param int $pid 菜单parent_menu_id
     * @return array
     */
    public function getMenuListFormat(array $data, int $pid = 0)
    {
        $list = [];
        foreach ($data as $row) {
            if ($row['parent_menu_id'] != $pid) {
                continue;
            }
            // 子菜单
            $children = $this->getMenuListFormat($data, $row['id']);
            $item = [
                'header' => $row['module_id'],
                'title' => $row['name'],
                'path' => $row['url'],
                'custom' => $row['class_style'],
                'children' => $children,
            ];

            $list[] = $item;
        }
        // 超管【展示】
        if ($pid == 0 && Yii::$app->user->identity->member->super_type == Member::SUPER_TYPE_SUPER_ADMIN) {
            $list[] = [
                'header' => "0",
                'title' => '开发配置',
                'path' => '/development',
                'custom' => 'ivu-icon-md-code-working',
                'children' => [
                    [
                        'header' => "0",
                        'title' => '菜单',
                        'path' => '/development/menu',
                        'custom' => '/',
                        'children' => [],
                    ],
                    [
                        'header' => "0",
                        'title' => '动作',
                        'path' => '/development/action',
                        'custom' => '/',
                        'children' => [],
                    ]
                ],
            ];
        }
        return $list;
    }

    /**
     * 获取角色权限列表
     * @param int $roleId
     * @param int $type 类型【0默认，1项目设置获取信息】
     * @return array
     */
    public function getRoleAuth(int $roleId): array
    {
        // 角色权限
        $menuList = self::getMenuList([$roleId]);
        $actionList = self::getActionList([$roleId]);
        $roleAuthList = [
            'menu' => $menuList ? array_column($menuList, 'id') : [],
            'action' => $actionList ? array_column($actionList, 'id') : [],
        ];
        // 权限列表【菜单+动作】
        $menuSerive = new MenuService();
        $authList = $menuSerive->getInnerActionList($roleId);

        // 格式化权限列表
        $level = 0;
        return $menuSerive->getInnerActionListFormat($authList, 0, $roleAuthList, $level+1);
    }

    /**
     * 删除菜单绑定关系
     * @param int|array $menuIds
     * @return int[]
     */
    public static function deleteMenuPermission($menuIds): array
    {
        $list = self::getRolePermissionListByPermissionIds(RolePermission::PERMISSION_TYPE_MENU, $menuIds);
        $list && RolePermission::deleteAll(['id' => array_column($list, 'id')]);
        return $list ? array_column($list, 'role_id') : [];
    }

    /**
     * 删除角色菜单绑定关系
     * @param int $roleId
     * @param int|array $menuIds
     * @return void
     */
    public static function deleteRoleMenuPermission(int $roleId, $menuIds): void
    {
        RolePermission::deleteAll([
            'role_id' => $roleId,
            'permission_id' => $menuIds,
            'permission_type' => RolePermission::PERMISSION_TYPE_MENU,
        ]);
    }

    /**
     * 删除动作绑定关系
     * @param int|array $actionIds
     * @return int[]
     */
    public static function deleteActionPermission($actionIds): array
    {
        $list = self::getRolePermissionListByPermissionIds(RolePermission::PERMISSION_TYPE_ACTION, $actionIds);
        $list && RolePermission::deleteAll(['id' => array_column($list, 'id')]);
        return $list ? array_column($list, 'role_id') : [];
    }

    /**
     * 删除角色动作绑定关系
     * @param int $roleId
     * @param int|array $actionIds
     * @return void
     */
    public static function deleteRoleActionPermission(int $roleId, $actionIds): void
    {
        RolePermission::deleteAll([
            'role_id' => $roleId,
            'permission_id' => $actionIds,
            'permission_type' => RolePermission::PERMISSION_TYPE_ACTION,
        ]);
    }
}
